import axios from 'axios' // 引入axios
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import { emitter } from '@/utils/bus.js'
import router from '@/router/index'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 120000
})
let acitveAxios = 0
let timer
const showLoading = () => {
  acitveAxios++
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    if (acitveAxios > 0) {
      emitter.emit('showLoading')
    }
  }, 400)
}

const closeLoading = () => {
  acitveAxios--
  if (acitveAxios <= 0) {
    clearTimeout(timer)
    emitter.emit('closeLoading')
  }
}
// http request 请求拦截器
service.interceptors.request.use(
  config => {
    if (!config.donNotShowLoading) {
      showLoading()
    }
    const userStore = useUserStore()
    config.headers['Authorization'] = userStore.token

    return config
  },
  error => {
    closeLoading()
    ElMessage({
      message: error,
      type: 'error'
    })
    return error
  }
)

// http response 响应拦截器
service.interceptors.response.use(
  response => {
    const userStore = useUserStore()
    closeLoading()
    if (response.status == 200 || response.status == '200') {
      if ((response.data.code === 200 || response.data.status === 200 && response.data.succeed) || response.request.responseType == 'blob') {
        if (response.config.url === '/login') {
          userStore.setToken(response.data)
        }
      } else if (
        response.data.status === 1000 ||
        response.data.status === 1001 ||
        response.data.status === 1002 ||
        response.data.status === 1003 ||
        response.data.status === 1004
      ) {
        console.log('111111111111111');
        return response.data
      }else {
        ElMessage({
          message: response.data.msg || '系统异常',
          type: 'error',
          duration: 10 * 1000
        })
      }

      return response.data
    }  else {
      ElMessage({
        message: response.data.msg || '系统异常',
        type: 'error',
        duration: 10 * 1000
      })
      return response.data
    }
  },
  error => {
    console.log(error);
    const userStore = useUserStore()
    closeLoading()
    if (!error.response) {
      ElMessageBox.confirm(`
        <p>检测到请求错误</p>
        <p>${error}</p>
        `, '请求报错', {
        dangerouslyUseHTMLString: true,
        distinguishCancelAndClose: true,
        confirmButtonText: '稍后重试',
        cancelButtonText: '取消'
      })
      return
    }

    switch (error.response.status) {
      // 捕获常见异常
      case 500:
        ElMessage({
          message: error.response.data.msg || '请求异常',
          type: 'error'
        })
        break
      case 404:
        ElMessageBox.confirm(`
          <p>检测到接口错误${error}</p>
          <p>错误码<span style="color:red"> 404 </span>：此类错误多为接口未注册（或未重启）或者请求路径（方法）与api路径（方法）不符</p>
          `, '接口报错', {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: '我知道了',
          cancelButtonText: '取消'
        })
        break
      case 401:
        userStore.LoginOut()
        ElMessage({
          message: error.response.data.msg || '请求异常',
          type: 'error'
        })
        break
      default:
        ElMessage({
          message: error.response.data.msg || '请求异常',
          type: 'error'
        })
    }
    // ElMessage({
    //   message: error.response.data.msg,
    //   type: 'error'
    // })
    return error
  }
)
export default service
